<?php
require_once 'mods/class_collection_iterator.php';

class Collection implements IteratorAggregate
{
    private $_onLoad;
    private $_isLoaded=false;
    private $_member=array();

    public function addItem($obj, $key = null)
    {
        $this->_checkCallback();
        if ($key) {
            if(isset($this->_member[$key])){
                echo 'not empty';
            } else {
                $this->_member[$key]=$obj;
            }
        } else {
            $this->_member[]=$obj;
        }
    }

    public function removeItem($key)
    {
        $this->_checkCallback();
        unset($this->_member[$key]);
    }

    public function getItem($key = null)
    {
        $this->_checkCallback();
        if ($key) {
            return $this->_member[$key];
        } else {
            return $this->_member[0];
        }
    }

    public function keys()
    {
        $this->_checkCallback();
        return array_keys($this->_member);
    }

    public function length()
    {
        $this->_checkCallback();
        return count($this->_member);
    }

    public function setLoadCallback($functionName, $objorclass=null)
    {
        if ($objorclass) {
            $callback=array($objorclass, $functionName);
        } else {
            $callback=$functionName;
        }
        if (!is_callable($callback,false,$callableName)) {
            echo $callableName.'not valid';
            return false;
        }
        $this->_onLoad=$callback;
    }

    public function setLoaded()
    {
		if (!$this->_isLoaded) {
			$this->_isLoaded=true;
		}
    }

    public function isLoaded()
    {
        return $this->_isLoaded;
    }

    private function _checkCallback()
    {
        if (isset($this->_onLoad) && !$this->_isLoaded) {
            $this->_isLoaded=true;
            call_user_func($this->_onLoad,$this);
        }
    }

    public function getIterator()
    {
        $this->_checkCallBack();
        return new CollectionIterator(clone $this);
    }
}
?>